package netty.handler;

import action.Dispatcher;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import netty.conn.listener.ConnectionListener;
import org.apache.log4j.Logger;

public class AccpetorHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = Logger.getLogger(AccpetorHandler.class);

    private ConnectionListener connectionListener;

    public AccpetorHandler(ConnectionListener connectionListener) {
        this.connectionListener = connectionListener;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        connectionListener.onConnectionComplete(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        connectionListener.onConnectionError(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof MessageHolder) {
            MessageHolder messageHolder = (MessageHolder) msg;
//            logger.info(messageHolder);
            Dispatcher.dispatch(messageHolder);
        }
    }
}
